package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @ApiOperation("营业额统计")
    public TurnoverReportVO Statistics(LocalDate begin, LocalDate end) {
        //根据传过来的时间对营销数据进行统计
        //时间不需要通过数据表了，直接遍历即可，先将每个时间(天)存放到list集合再去转成字符串，因为响应数据要的是字符串
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);//将第一天添加
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        //这样就得到了所有日期集合
        //遍历日期，查询对应的数据
        //定义一个集合用于储存对应的营业额
        List<Double> reportList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //时间区间用于查询当天营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//            reportList.add(number);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double aDouble = reportMapper.selReport(map);
            aDouble = aDouble == null ? 0.0 : aDouble;
            reportList.add(aDouble);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .turnoverList(StringUtils.join(reportList, ","))
                .build();
    }

    @ApiOperation("用户统计")
    public UserReportVO userTics(LocalDate begin, LocalDate end) {
        //根据传过来的时间对营销数据进行统计
        //时间不需要通过数据表了，直接遍历即可，先将每个时间(天)存放到list集合再去转成字符串，因为响应数据要的是字符串
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);//将第一天添加
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        //这里需要每天新增用户数和截止当天用户总数
        List<Integer> everyDayList = new ArrayList<>();
        List<Integer> allList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //时间区间用于查询当天营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("endTime", endTime);

            Integer totalUSer = reportMapper.selUserStis(map);
            allList.add(totalUSer);

            map.put("beginTime", beginTime);
            Integer dayStis = reportMapper.selUserStis(map);//dayStis
            everyDayList.add(dayStis);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .newUserList(StringUtils.join(everyDayList, ","))
                .totalUserList(StringUtils.join(allList, ","))
                .build();
    }

    @ApiOperation("订单统计功能")
    public OrderReportVO ordersReport(LocalDate begin, LocalDate end) {
        /**
         * 订单统计功能
         * TODO
         **/

        List<LocalDate> list = new ArrayList<>();
        list.add(begin);//将第一天添加
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        //订单总数、有效订单数、订单完成率、日期列表、订单列表、有效订单列表，都是以，隔开的字符串
        //List<Integer> everyDayList = new ArrayList<>();
        List<Integer> totalCount = new ArrayList<>();//每天总订单数
        List<Integer> validOrdercountList = new ArrayList<>();//有效订单数
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer totalAll = turnOverStat(beginTime, endTime, null);
            totalCount.add(totalAll);
            Integer dayTotal = turnOverStat(beginTime, endTime, Orders.COMPLETED);
            validOrdercountList.add(dayTotal);
//            totalCount.add(totalAll);
            //当天订单总数、注：已取消的订单不能算
        }

        Integer total = totalCount.stream().reduce(Integer::sum).get();
        Integer day = validOrdercountList.stream().reduce(Integer::sum).get();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);

        //时间区间的订单总数
        Integer allCount = reportMapper.orderCount(map);

        // 时间区间的有效订单总数
        map.put("status", Orders.COMPLETED);
        Integer validCount = reportMapper.orderCount(map);

        //订单完成率
//        Double completion = (double) validCount / allCount;
        Double completion = (double) total / day;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(list, ","))
                .orderCountList(StringUtils.join(totalCount, ","))
                .validOrderCountList(StringUtils.join(validOrdercountList, ","))
                .totalOrderCount(total) // allCount
                .validOrderCount(day)//validCount
                .orderCompletionRate(completion)
                .build();
    }

    /**
     * 导出运营报表
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //步骤分析
        //查询数据
        LocalDate localDate = LocalDate.now().minusDays(30);
        LocalDate now = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //填写对应的数据到表格中
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板创建一个Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);

            //填充数据
            XSSFSheet sheet1 = excel.getSheet("sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + localDate + "--" + now);

            //第四行第3格填充营业额
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());

            //第四行第5格填充订单完成率
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());

            //第四行第7格填充新增用户数
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());

            //第五行第3格填充有效订单
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());

            //第四行第5格填充平均客价
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());


            //第8行第2格开始，填写单日的对应数据
            for (int i = 0; i < 30; i++) {
                //起始时间计算
                LocalDate theTime = localDate.plusDays(i);
//                LocalDate theTime = LocalDate.now().minusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(theTime, LocalTime.MIN),
                        LocalDateTime.of(theTime, LocalTime.MAX));

                //日期
                XSSFRow row = sheet1.getRow(i + 7);
                row.getCell(1).setCellValue("时间：" + theTime);
                //当天营业额
                row.getCell(2).setCellValue(businessData1.getTurnover());
                //当天有效订单
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                //当天订单完成率
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                //当天平均客价
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                //当天新增用户数
                row.getCell(6).setCellValue(businessData1.getNewUsers());


            }
            //下载到用户客户端
            //首先要创建一个输出流将Excel文件下载到客户端浏览器--OutputStream流
            ServletOutputStream stream = response.getOutputStream();
            //再写出
            excel.write(stream);
            stream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //导出数据
    }

    private Integer turnOverStat(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        Integer total = reportMapper.totalOrderCount(map);
        return total;
    }

}
